package main

import (
	_ "GraduationProject/public/tools"

	"GraduationProject/public/db"
	"GraduationProject/public/models"
	"GraduationProject/public/tools"
	"context"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"github.com/olivere/elastic"
	"strconv"
	"time"
)

func init() {
	fmt.Println(tools.Conf)
	db.ElasticSearchConnect()
}

var (
	index = "test"
)

func main() {
	router := gin.New()

	router.GET("/save", Save)
	router.GET("search", Search)

	if err := router.Run(":8085"); err != nil {
		panic(err)
	}
}

func Save(c *gin.Context) {
	_type := c.Query("type")
	url := c.Query("url")
	functionName := c.Query("function_name")
	_error := c.Query("error")
	result := c.Query("result")

	fmt.Println(_type, url, functionName, _error, result)

	record := models.Record{
		Model: gorm.Model{
			ID:        1,
			CreatedAt: time.Now(),
			UpdatedAt: time.Now(),
			DeletedAt: nil,
		},
		NotElastic:   false,
		SeedID:       1,
		Url:          url,
		FunctionName: functionName,
		Error:        _error,
		Result:       result,
	}
	s := save(index, _type, record)

	c.JSON(200, gin.H{
		"status": 200,
		"value":  s,
	})
}

func Search(c *gin.Context) {
	query := c.Query("query")
	from := c.Query("from")
	i, err := strconv.Atoi(from)
	if err != nil {
		i = 0
	}
	result := search(index, query, i)

	c.JSON(200, gin.H{
		"status": 200,
		"value":  result,
	})
}

func save(index, _type string, body models.Record) (result string) {
	response, err := db.ElasticClient.Index().
		Index(index).Type(_type).BodyJson(body).
		Do(context.Background())
	if err != nil {
		return err.Error()
		//panic(err)
	}

	bytes, _ := json.Marshal(response)
	return string(bytes)
	//fmt.Println("save:", string(bytes))
}

func search(index, query string, from int) (result string) {
	q := elastic.NewQueryStringQuery(query)
	//q := elastic.NewMatchPhraseQuery("result", query)

	res, err := db.ElasticClient.Search(index).
		Query(q).
		From(from).Do(context.Background())
	if err != nil {
		return err.Error()
		//panic(err)
	}

	bytes, _ := json.Marshal(res)
	return string(bytes)
	//fmt.Println("save:", string(bytes))
}
